package com.we.wfc.common.comparator;


import com.we.wfc.common.annotation.TreeSort;
import com.we.wfc.common.utils.ConverterUtil;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.Comparator;

/**
 * @Description: 树状类型
 * @Author:Liangzy(Feeling)
 * @Date:Create in 2019/12/30 2:25 下午
 */
public class TreeCompartor<T> implements Comparator<T> {

    private Field sort;

    private String sortType = "asc";

    public TreeCompartor(Field sortField) {
        this.sort = sortField;
        TreeSort sort = sortField.getAnnotation(TreeSort.class);
        if (ConverterUtil.isNotEmpty(sort)) {
            this.sortType = sort.value();
        }
        this.sort.setAccessible(true);
    }

    public TreeCompartor(Field sortField, String sortType) {
        this.sort = sortField;
        this.sortType = sortType;
        this.sort.setAccessible(true);
    }

    @Override
    public int compare(T t1, T t2) {
        try {
            int result = 0;
            Object o1 = this.sort.get(t1);
            Object o2 = this.sort.get(t2);
            if (o1 instanceof Integer) {
                result = ConverterUtil.toInteger(o1).compareTo(ConverterUtil.toInteger(o2));
            } else if (o1 instanceof Double) {
                result = ConverterUtil.toDouble(o1).compareTo(ConverterUtil.toDouble(o2));
            } else if (o1 instanceof BigDecimal) {
                result = ConverterUtil.toBigDecimal(o1).compareTo(ConverterUtil.toBigDecimal(o2));
            } else {
                String c1 = ConverterUtil.toString(o1, "");
                String c2 = ConverterUtil.toString(o2, "");
                result = c1.compareTo(c2);
            }
            // 升序
            if (sortType.equalsIgnoreCase("asc")) {
                return result;
            } else {
                // 降序
                return -result;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
